package com.xqboss.common.enums;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.xqboss.common.exception.ServiceException;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author Trent
 * @date 2023/8/21
 */

public class EnumJsonDeserializer extends JsonDeserializer<BaseEnum<Integer>> implements ContextualDeserializer {

    private Class<? extends BaseEnum<Integer>> propertyClass; // 记录枚举字段的类，用于获取其定义的所有枚举值

    public EnumJsonDeserializer() {
    }

    public EnumJsonDeserializer(Class<? extends BaseEnum<Integer>> propertyClass) {
        this.propertyClass = propertyClass;
    }

    @Override
    public BaseEnum<Integer> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
        int code = p.getValueAsInt();
        return Arrays.stream(propertyClass.getEnumConstants())
                .filter( item -> item.getValue() == code)
                .findFirst()
                .orElseThrow(()-> new ServiceException("不支持的类型！！"));
    }

    @SuppressWarnings({"unchecked"})
    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws
            JsonMappingException {
        return new EnumJsonDeserializer((Class<? extends BaseEnum<Integer>>) property.getType().getRawClass()); // 获取枚举字段的类型Class
    }

}
